

import {useState,useRef , useEffect, useCallback} from "react"
// useCallback
// useCallback 真正目的是在于缓存实例函数方法  减少不必要的渲染 componentWillUpdate && shouldComponentUpdate


export function HooksFour(){
  const [count,setCount] = useState(1111)
  const [msg,setMsg] = useState("2107--转介绍呢")
  const [list,setList] = useState(["Vue","React","小程序","Fullter","TypeScript"])
  const inp = useRef()
  const ele = useRef()
  useEffect(()=>{
    console.log("useEffect --> componentDidMount / componentDidUpdate / componentWillUnmount")
    ele.current.style.color = "red"
    ele.current.style.fontSize = "30px"
  },[])
  const changeMsg = ()=>{
    setMsg(inp.current.value)
    inp.current.value = ''
  }
  const myList = useCallback(()=>{
    console.log("真正目的是在于缓存实例函数方法  减少不必要的渲染 shouldComponentUpdate ")
    return list.join(" & ")
  },[list])
  // 不写 [] 条件 retrun true 所有修改都可以更新 
  // [ ]  retrun false  所有修改都不可以更新 
  // [list]
  return (
    <div>
      <h2> Hooks - 4 -  useCallback</h2>
      <p ref={ele} > useCallback -- shouldComponentUpdate  询问是否可以更新 </p>
      <h2>count --- {count}</h2>
      <h2>msg == {msg}</h2>
      <hr/>
      <button onClick={()=>setCount(count+10)} >点击修改 count </button>
      <p>
        <input type="text" value={msg}  ref={inp} onChange={changeMsg}/>
      </p>
      <div>
        {list.join(" ~ ")}
      </div>
      <button onClick={()=>setList([...list,"JS","JAVA","Node","PYTHON","GO","GOLANG"])} >点击修改list </button>
      <hr/>
      <ChildOne
      msg={msg}
      count={count}
      list={list}
      myList={myList}
      ></ChildOne>
    </div>
  )
}


 function ChildOne( { msg,count,list , myList }){
   return (
     <div>
       <h2> ChildOne - ChildOne-  1 </h2>
       <p>count == {count }</p>
       <p>msg == {msg }</p>
       <p> list = {list.join(" * ")}</p>
       <p> myList =  {myList()}</p>
     </div>
   )
 }



//  useCallback  VS   useMemo  
//  useMemo是在DOM更新前触发的，就像官方所说的，类比生命周期就是shouldComponentUpdate

//  使用useMemo可以帮助我们优化性能，让react没必要执行不必要的函数
//  由于复杂数据类型的地址可能发生改变，于是传递给子组件的props也会发生变化，这样还是会执行不必要的函数，所以就用到了useMemo这个api
//  useCallback是useMemo的语法糖
